<?php

namespace App\Service\Third;
use App\Service\BaseService;
use App\Model\PayOrder;
use App\Constants\ErrorCode;

/**
 * 获取OpenId
 */
class GetDougongOpenidService extends BaseService
{

    //支付链接
    const PAY_LINK = "https://api.huifu.com/v2/trade/payment/jspay";
    //系统号(商户号)
   // const SYS_ID ='6666000167474071';
    //const SYS_ID = '6666000164636033';
    const SYS_ID ='6666000169395354';

    //产品号
    const PRODUCT_ID = 'EDUSTD';
    //商户号
    // const HUIFU_ID = '6666000167474071';
    //const HUIFU_ID = '6666000165631783';
    const HUIFU_ID = '6666000169395354';
    //回调地址
    const NOTIFY_URL = 'https://api.jun131419.com/callback/dougong_pay';
    //APPID
    //const WX_APPID = 'wx18af8941701fa8a1';//小君

    
    //const WX_APPID = 'wxb7e1f844fef823e2';

    const WX_APPID = 'wxa4887f6d4b618579';//新
    //WX_SECRET
   // const WX_SECRET = 'aa4e49fab827c7b6611629761219d8e4';

    //const WX_SECRET = 'b22f591c0570e29e91a329c343223aa0';//小君

    const WX_SECRET = '2854e1ed294018bddc4a701e3d414655';//新
    
    public function handle()
    {
        $callbackArray = $this->request->all();

 
        // echo '<pre>';

      //  print_r($callbackArray );
       // echo '</pre>';
       // exit('aa');
        //file_put_contents("0605.txt", json_encode($callbackArray));



        log_info(__CLASS__ . "==" . json_encode($callbackArray));


        $openid = $this->getOpenid($callbackArray['code']);
        // file_put_contents("060501.txt", json_encode($openid));
        //  file_put_contents("0605011.txt", $openid);

       // $openid ="oJRph7F2vLLoFq2oyejseN1jrYXw";
//	return $openid;
	$payResult = $this->huifuPay($callbackArray['orderId'],$openid);
	//return $openid;
	return $payResult;
    }

    //获取openid
    private function getOpenid($code){
        // 请求获取openid
        $url = "https://api.weixin.qq.com/sns/jscode2session";
        // $params = [
        //     'appid' => self::WX_APPID,
        //     'secret' => self::WX_SECRET,
        //     'js_code' => $code,
        //     'grant_type' => 'authorization_code'
        // ];


        

	//return $params;	
       // $response = file_get_contents($url . '?' . http_build_query($params));

        $appid =  self::WX_APPID;
        $secret =  self::WX_SECRET;

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";

        $response = $this->httpRequest($url);
        //$data = json_decode($response, true);

       // file_put_contents("0605012.txt", $response);
//	return $response;
	$data = json_decode($response, true);

        if (isset($data['openid'])) {
            $openid = $data['openid'];
            return $openid;
            // 存储openid用于后续支付
        } else {
            // 处理错误（如code失效）
            return "获取openid失败: " . $data['errmsg'];
        }
    }

    //调用汇付支付接口
    private function huifuPay($orderId,$openid) {
        //私钥
        $rsaPrivateKey = config('dougong3.private_key');

        $orderInfo = PayOrder::getByOutTradeNo($orderId);
        //查pay_order表中的信息
        //file_put_contents("060502.txt", json_encode($orderInfo));

        $rounded = round($orderInfo['total_amount']/100,2);
        $trans_amt = number_format($rounded, 2, '.', ''); // 格式化为两位小数
        $data = [

	       //日期格式
	        'req_date' => date('Ymd',time()),
            //'req_date' => $orderInfo['updated_at'],
            //请求流水号
            'req_seq_id' => $orderInfo['out_trade_no'],
            'huifu_id' => self::HUIFU_ID,
            'goods_desc' => '充值',
            //交易类型
            'trade_type' => 'T_MINIAPP',
            // 交易金额
            'trans_amt' => $trans_amt,
            'notify_url' => self::NOTIFY_URL,
            'wxdata' => [
                'sub_appid' => self::WX_APPID,
                'sub_openid' => $openid,
            ],
            "pay_scene"=>"02",
            // "time_expire"=>date("YmdHms",time()+120),
            "limit_pay_type"=>"NO_CREDIT",
            "delay_acct_flag"=>"N",
            "fq_mer_discount_flag"=> "N",

        ];
        $post_array = [
            'sys_id' => self::SYS_ID,
            'product_id' => self::PRODUCT_ID,
            'data' => $data,
        ];
        ksort($data);
        //return [$data];


         

        $sign_json = json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        $sign = self::sha_with_rsa_sign($sign_json,$rsaPrivateKey);

        $post_array['sign'] = $sign;
        ksort($post_array);

       // file_put_contents("060503.txt", json_encode($post_array));




        $result = self::curlPost(self::PAY_LINK, $post_array);
        //$result = self::sendHttp(self::PAY_LINK, json_encode($post_array));

        $result['data']['payInfo'] = json_decode($result['data']['pay_info'],true);
        return $result;

	   
	   return $json_payInfo;

	//$pay_data = array();
	//return $pay_data;
    }

    /*
    * 发送请求
    * @param $url
    * @param $param
    * @return bool|mixed
    * @throws Exception
    */
    static function curlPost($url, $postData){
        // 初始化 cURL
        $ch = curl_init();

        // 配置 cURL 选项
        curl_setopt_array($ch, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true, // 返回响应而不是直接输出
            CURLOPT_POST => true, // 使用 POST 方法
            CURLOPT_POSTFIELDS => json_encode($postData), // 发送 JSON 数据
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
               // 'Authorization: Bearer your_access_token' // 认证头
            ],
            CURLOPT_TIMEOUT => 60, // 超时设置
            CURLOPT_SSL_VERIFYPEER => true // 生产环境应保持为 true
        ]);

        // 执行请求
        $response = curl_exec($ch);

       // file_put_contents("060501.txt", $response);

        // 检查错误
        if (curl_errno($ch)) {
            throw new Exception('cURL Error: ' . curl_error($ch));
        }

        // 获取 HTTP 状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
      //  return $httpCode;
        // 关闭 cURL 资源
        curl_close($ch);

         // 在curlPost方法中添加调试日志
//file_put_contents('huifu_req.log', 
 //   "【Request】\n".json_encode($postData,JSON_PRETTY_PRINT)."\n".
 //   "【Response】\n".$response."\n\n",
 //   FILE_APPEND);


        // 处理响应
        if ($httpCode === 200) {
            $data = json_decode($response, true);
            return $data;
            // 处理返回的数据
        } else {
            // 处理错误
            return '请求失败';
            //file_put_contents("060599.txt", $httpCode);
            //throw new Exception("API 请求失败，状态码: $httpCode");
        }
    }

    static function sendHttp($url,$jsonObject){

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, true); 
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonObject); // POST 数据
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json'
        ));
        curl_setopt($ch, CURLOPT_TIMEOUT, 60); // 设置最大执行时间为60秒

        $respMap = curl_exec($ch);
        file_put_contents("0605088.txt", $respMap);

        // 获取 HTTP 状态码
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $httpCode;


        return $respMap;
    }


    function httpRequest($url, $method = 'GET', $data = []) {
        $ch = curl_init();
        if ($method === 'POST') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 忽略 SSL 验证，生产环境建议配置证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $response = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Curl error: '. curl_error($ch);
        }
        curl_close($ch);
        return $response;
    }



    /**
     * 私钥加签（对数据源排序），可用于 V2 版本接口数据加签
     *
     * @param array $data 原数据( 排序后的json字符串; 数组参数排序后转json字符串(数据的中文和斜杠均不转码):
     *
     * @param string $rsaPrivateKey 私钥
     * @param int $alg 默认 OPENSSL_ALGO_SHA256
     *
     * @return string 签名串
     */
    function sha_with_rsa_sign($data, $rsaPrivateKey, $alg=OPENSSL_ALGO_SHA256){
        // ksort($data);
        // json_encode($data, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
        $key = "-----BEGIN PRIVATE KEY-----\n".wordwrap($rsaPrivateKey, 64, "\n", true)."\n-----END PRIVATE KEY-----";
        $signature= '';
        try {
            openssl_sign($data, $signature, $key, $alg);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
        return base64_encode($signature);
    }
}
